package com.nova.android.tvlauncher.ui.adapter.atv

import android.animation.ValueAnimator
import android.view.View
import android.view.animation.DecelerateInterpolator
import androidx.core.content.ContextCompat
import androidx.leanback.widget.HorizontalGridView
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.databinding.TabItemNavigationBinding

object HomeTabAdapter {
    // 状态控制
     var selectedPosition = 0 // 初始无选中项
     var lastFocusedPosition = -1 // 记录最后获得焦点的位置

     fun bindData(
        binding: TabItemNavigationBinding,
        modelPosition: Int,
        models: List<Any>,
        itemView: View,
        tabLayout: HorizontalGridView
    ) {
        binding.tvNavigationItemLabel.text = models[modelPosition] as String
        // 动态设置指示器宽度
        binding.tvNavigationItemLabel.post {
            val params = binding.indicator.layoutParams.apply {
                width = binding.tvNavigationItemLabel.paint.measureText(models[modelPosition] as String).toInt()
            }
            binding.indicator.layoutParams = params
        }


        // 初始化视图状态
        updateItemState(binding, modelPosition,itemView)

        itemView.setOnFocusChangeListener { _, hasFocus ->
            lastFocusedPosition = if (hasFocus) modelPosition else -1
            if (hasFocus) {
                setSelectedPosition(modelPosition,models,tabLayout) // 获得焦点时设为选中项
                onTabSelectedListener?.invoke(modelPosition)
            }
            updateItemState(binding, modelPosition,itemView)
        }
    }

    private var onTabSelectedListener: ((position: Int) -> Unit)? = null
    fun onTabSelected(listener: (position: Int) -> Unit) {
        onTabSelectedListener = listener
    }

    // 外部可调用的选中项设置方法
    fun setSelectedPosition(position: Int, models: List<Any>,tabLayout: HorizontalGridView) {
        if (position in models.indices && position != selectedPosition) {
            val prevSelected = selectedPosition
            selectedPosition = position
            if (prevSelected != -1) tabLayout.adapter?.notifyItemChanged(prevSelected)
            tabLayout.adapter?.notifyItemChanged(selectedPosition)
        }
    }

    private fun updateItemState(binding: TabItemNavigationBinding, position: Int, itemView: View) {
        val isSelected = position == selectedPosition
        val isFocused = position == lastFocusedPosition

        // 设置文字颜色
        binding.tvNavigationItemLabel.setTextColor(
            ContextCompat.getColor(
                itemView.context,
                when {
                    isFocused -> R.color.tab_selected_color
                    isSelected -> R.color.tab_selected_unfocused_color
                    else -> R.color.tab_unselected_color
                }
            )
        )

        // 指示器控制（仅选中项显示）
        if (isSelected) {
            binding.indicator.visibility = View.VISIBLE

            val targetColor = ContextCompat.getColor(
                itemView.context,
                if (isFocused) R.color.tab_selected_color
                else R.color.tab_selected_unfocused_color
            )
            binding.indicator.setBackgroundColor(targetColor)

            // 动画处理：非焦点选中项时缩短指示器宽度
            if (!isFocused) {
                val currentWidth = binding.indicator.width
                val targetWidth = (binding.tvNavigationItemLabel.paint.measureText(
                    binding.tvNavigationItemLabel.text.toString()
                ) * 0.55).toInt() // 缩短到原来的 60% 为例

                if (currentWidth != targetWidth) {
                    val animator = ValueAnimator.ofInt(currentWidth, targetWidth).apply {
                        duration = 500L
                        interpolator = DecelerateInterpolator()
                        addUpdateListener { animation ->
                            val newWidth = animation.animatedValue as Int
                            binding.indicator.layoutParams = binding.indicator.layoutParams.apply {
                                width = newWidth
                            }
                            binding.indicator.requestLayout()
                        }
                    }
                    animator.start()
                }
            }else{
                val currentWidth = binding.indicator.width
                val targetWidth = (binding.tvNavigationItemLabel.paint.measureText(
                    binding.tvNavigationItemLabel.text.toString()
                ) ).toInt() // 缩短到原来的 60% 为例

                if (currentWidth != targetWidth) {
                    val animator = ValueAnimator.ofInt(currentWidth, targetWidth).apply {
                        duration = 500L
                        interpolator = DecelerateInterpolator()
                        addUpdateListener { animation ->
                            val newWidth = animation.animatedValue as Int
                            binding.indicator.layoutParams = binding.indicator.layoutParams.apply {
                                width = newWidth
                            }
                            binding.indicator.requestLayout()
                        }
                    }
                    animator.start()
                }else{
                    val animator = ValueAnimator.ofInt((currentWidth*0.55).toInt(), targetWidth).apply {
                        duration = 500L
                        interpolator = DecelerateInterpolator()
                        addUpdateListener { animation ->
                            val newWidth = animation.animatedValue as Int
                            binding.indicator.layoutParams = binding.indicator.layoutParams.apply {
                                width = newWidth
                            }
                            binding.indicator.requestLayout()
                        }
                    }
                    animator.start()
                }
            }
        } else {
            binding.indicator.visibility = View.GONE
        }
    }


}